#include "app_pool.h"
#include <pthread.h>
#include <mqueue.h>
#include "log/log.h"
#include <unistd.h>
#include <stdlib.h>

// 队列名称
static char *mq_name = "/app_pool_mq";
// 消息描述符
static mqd_t mqt;
// 将线程池的数量传递出来以供其他函数使用
static int thread_count = 0;
// 线程池的初始化
static pthread_t *thread_pool = NULL;

static void *pool_thread_fun(void *arg){
    Task task;
    while (1){
        // 从消息队列中获取消息
        ssize_t len = mq_receive(mqt, (char *)&task, sizeof(Task), NULL);
        if (len == sizeof(Task))
        {
            task.task(task.arg);
        }
    }
}

int app_pool_init(int size)
{
    // 创建消息队列
    struct mq_attr attr;
    attr.mq_maxmsg = 5;
    attr.mq_msgsize = sizeof(Task);
    mqt = mq_open(mq_name, O_CREAT | O_RDWR, 0644, &attr);
    if (mqt == -1)
    {
        log_error("mq_open error");
        return -1;
    }

    // 创建线程池
    thread_count = size;
    thread_pool = (pthread_t *)malloc(sizeof(pthread_t) * size);
    for (int i = 0; i < size; i++){
        pthread_create(thread_pool + i, NULL, pool_thread_fun, NULL);
    }

    return 0;
}

void app_pool_close(void)
{
    // 关闭线程池
    for (int i = 0; i < thread_count; i++)
    {
        pthread_cancel(thread_pool[i]);
        pthread_join(thread_pool[i], NULL);
    }
    free(thread_pool);

    // 关闭消息队列
    mq_close(mqt);
    mq_unlink(mq_name);
}

void app_pool_registerTask(int (*task)(void *), void *arg)
{
    // 创建任务
    Task newtask = {
        .task = task,
        .arg = arg
    };
    // 将任务放入消息队列
    mq_send(mqt, (char *)&newtask, sizeof(Task), 0);
}
